import axios from 'axios'
import { Toast } from 'vant'
import { removeLocal, getLocal } from '@/utils/local'
import store from '@/store'
import router from '@/router'
// 取消方法集合
const cancelArr = []
// 取消某个接口
window.cancelAxios = function (url = '', cancelAll = false) {
  cancelArr.filter(item => {
    if (cancelAll) {
      item.c()
      return false
    } else {
      if (url === item.url) {
        item.c()
        return false
      } else {
        return true
      }
    }
  })
}
const _address = axios.create({
  baseURL: process.env.VUE_APP_URL
})
// 请求拦截
_address.interceptors.request.use(function (config) {
  if (config.needToken) {
    config.headers.authorization = `Bearer ${getLocal('token')}`
  }
  window.cancelAxios(config.url)
  // 生成关闭方法
  config.cancelToken = new axios.CancelToken(cancel => {
    cancelArr.push({
      url: config.url,
      c: cancel
    })
  })
  return config
}, function (error) {
  return Promise.reject(error)
})
// 响应拦截
_address.interceptors.response.use(function (response) {
  if (response.data.code === 200) {
    return response
  } else if (response.data.code === 401 || response.data.code === 403) {
    Toast.fail(response.data.message)
    // 删除token
    removeLocal('token')
    // 修改登录状态
    store.commit('setIsLogin', false)
    // 跳转至登录页
    router.push('/login')
    return Promise.reject(new Error(response.data.code))
  } else {
    Toast.fail(response.data.message)
    return Promise.reject(new Error(response.data.code))
  }
}, function (error) {
  Promise.reject(error)
  // console.log(error)
})
/* const _ajax = function (obj) {
  return new Promise((resolve, reject) => {
    _address(obj).then(res => {
      resolve(res)
    }).catch(err => {
      window.console.log(err)
    })
  })
} */
export default _address
